import axios from 'axios';
import { browser, os } from './ua';


function checkErrorCode(response) {
  // console.log('---response response---', response);
  const status = response.status;
  if (status === 200) {
    // 判断响应头是否有token_new，有的话替换本地的token
    // 不知道场景是什么，目前没有更改global.store里面的token，因为里面的token只需要做有没有的判断
    const token = response.headers.token_new;
    if (token) {
      const url = response.config.url;
      const noUrl = /account\/gettoken/.test(url) && /account\/isconfirmed/.test(url);
      if (!noUrl) {
        const preToken = window.localStorage.getItem('token');
        const newToken = `Bearer ${token}`;
        if (newToken !== preToken) {
          console.log('--change new token--');
          window.localStorage.setItem('token', newToken);
        }
      }
    }
    return { ...response.data, status };
  } else {
    const error = new Error(response.data.message);
    throw error;
  }
}

export function getDeviceHeaders() {
  let currentLocale = window.localStorage.getItem('currentLocale') || '';
  return {
    device: 'WEB',
    version: process.env.REACT_APP_VERSION,
    Language: currentLocale,
    Sysmark: `${os.name} ${os.version}, ${browser.name} ${browser.version}`
  };
}

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [options] The options we want to pass to "fetch"
 * @return {Promise<object>}  An object containing either "data" or "err"
 */
export default function request(url, options) {
  const opts = { ...options };
  const defaultHeaders = {
    'Content-Type': 'application/json',
    ...getDeviceHeaders()
  };

  if (!/login/.test(url) && !/account/.test(url)) {
    defaultHeaders.Authorization = window.localStorage.getItem('token');
  }

  opts.headers = options.headers ? { ...defaultHeaders, ...options.headers }
    : defaultHeaders;

  if (options.body) {
    opts.data = options.body;
  }

  return axios(url, opts)
    .then(checkErrorCode, error => {
      // console.log('---error error---', error, error.request, error.message);
      if (error.response) {
        const { data, status } = error.response;
        if (data.message === '请先登录' && status === 401) {
          return { data, status, message: '用户过期，请重新登录' };
        }
      } else if (error.request) {
        console.log('请求发生错误');
        return { data: null, message: error.message };
      } else {
        // Something happened in setting up the request that triggered an Error
        console.log('Error', error.message);
        return { data: null, message: error.message };
      }
    })
    .catch(error => {
      console.log('---catch err---', error);
    });
}
